using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SLIITPro.Core
{
    public static class Utility
    {

        public static byte[] HashPassword(string plainMessage)
        {
            byte[] data = Encoding.UTF8.GetBytes(plainMessage);
            using (HashAlgorithm sha = new SHA256Managed())
            {
                byte[] encryptedBytes = sha.TransformFinalBlock(data, 0, data.Length);
                return encryptedBytes.ToArray();
            }
        }


        public static void ClearContent(Control parent)
        {
            foreach (Control c in parent.Controls)
            {
                if ((c.GetType() == typeof(TextBox)))
                {
                    ((TextBox)(c)).Text = string.Empty;
                }
                else if ((c.GetType() == typeof(DropDownList)))
                {
                    ((DropDownList)(c)).SelectedIndex = -1;
                }
                if (c.HasControls())
                {
                    ClearContent(c);
                }
            }
        }

        public static string BuildTemplate(Control sendMail)
        {
            var stringBuilder = new StringBuilder();
            var stringWriter = new StringWriter(stringBuilder);
            var htmlTextWriter = new HtmlTextWriter(stringWriter);
            sendMail.RenderControl(htmlTextWriter);
            htmlTextWriter.Close();
            return stringBuilder.ToString();
        }


        public static bool IsNumberId(string context)
        {
            try
            {
                int.Parse(context);
                return true;
            }
            catch
            {
                return false;
            }
        }
        public static string CleanStrContent(string content)
        {
            content = content.Replace("\\", string.Empty)
                             .Replace("|", string.Empty)
                             .Replace("(", string.Empty)
                             .Replace(")", string.Empty)
                             .Replace("[", string.Empty)
                             .Replace("]", string.Empty)
                             .Replace("*", string.Empty)
                             .Replace("?", string.Empty)
                             .Replace("}", string.Empty)
                             .Replace("{", string.Empty)
                             .Replace("^", string.Empty)
                             .Replace("+", string.Empty);

            string[] words = content.Split(new char[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
            var sb = new StringBuilder();
            foreach (string t in words)
            {
                string word = t.ToLowerInvariant().Trim();
                if (word.Length > 1)
                    sb.Append(word + " ");
            }

            return sb.ToString();
        }

        public static string GenerateId()
        {
            var i = Guid.NewGuid().ToByteArray().Aggregate<byte, long>(1, (current, b) => current * (b + 1));
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }

        public static string GetCountry(string prefix)
        {
            string country = null;
            if (prefix.Trim().ToUpperInvariant() == "LK")
            {
                country = "Sri Lanka";
            }
            else
            {
                foreach (var culture in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
                {
                    RegionInfo region = new RegionInfo(culture.Name);

                    if (prefix.Trim().ToUpperInvariant() == region.TwoLetterISORegionName.ToUpperInvariant())
                    {
                        country = region.EnglishName;
                    }

                }
            }
            return country;
        }

        public static void BindCountries(DropDownList ddlCountry)
        {
            var dictionary = new StringDictionary();
            var list = new List<string>();

            foreach (var culture in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
            {
                RegionInfo region = new RegionInfo(culture.Name);
                if (!dictionary.ContainsKey(region.EnglishName))
                    dictionary.Add(region.EnglishName, region.TwoLetterISORegionName.ToUpperInvariant());

                if (!list.Contains(region.EnglishName))
                    list.Add(region.EnglishName);
            }

            if (!dictionary.ContainsValue("LK"))
            {
                dictionary.Add("Sri Lanka", "LK");
                list.Add("Sri Lanka");
            }
            list.Sort();

            ddlCountry.Items.Add(new ListItem("[Not specified]", ""));
            foreach (string key in list)
            {
                ddlCountry.Items.Add(new ListItem(key, dictionary[key]));
            }
        }


        public static void SendMailMessageAsync(string email, string name, string subject, string message)
        {
            ThreadPool.QueueUserWorkItem(delegate { SendEmail(email, name, subject, message); });
        }


        public static void SendEmail(string email, string name, string subject, string message)
        {
            try
            {
                System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage();
                MyMailMessage.To.Add(email);
                MyMailMessage.From = new System.Net.Mail.MailAddress(EmailSettings.FromMailAddress, name);
                MyMailMessage.Subject = subject;
                MyMailMessage.Body = message;
                MyMailMessage.IsBodyHtml = true;
                MyMailMessage.Priority = System.Net.Mail.MailPriority.High;
                System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential(EmailSettings.FromMailAddress, "sliitpro");
                System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient(EmailSettings.SmtpClient, (int)EmailSettings.SmtpPort.Gmail);
                mailClient.EnableSsl = true;
                mailClient.UseDefaultCredentials = false;
                mailClient.Credentials = mailAuthentication;
                mailClient.Send(MyMailMessage);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /*public static void SendMessage(string subject, string NameDispay, string body, string To)
        {
            try
            {
                var MyMailMessage = new MailMessage();
                MyMailMessage.To.Add(To);
                MyMailMessage.From = new MailAddress("sliitpro2@gmail.com", NameDispay);
                MyMailMessage.Subject = subject;
                MyMailMessage.Body = body;
                MyMailMessage.IsBodyHtml = true;
                MyMailMessage.Priority = MailPriority.High;
                var mailAuthentication = new System.Net.NetworkCredential("sliitpro2@gmail.com", "sliitpro");
                //System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("relay-hosting.secureserver.net", 25);
                //System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtpout.secureserver.net", 25);
                var mailClient = new SmtpClient("smtp.gmail.com", 465)
                                     {
                                         EnableSsl = true,
                                         UseDefaultCredentials = false,
                                         Credentials = mailAuthentication
                                     };
                mailClient.Send(MyMailMessage);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }*/

    }
}